//
//  STNativeAdmobView.swift
//  iPhone
//
//  Created by Toj on 5/30/23.
//

import UIKit
import GoogleMobileAds

class STNativeAdmobView: UIView {
    
    var admobModel: STAdmobModel?
    
    var nativeAdObject: GADNativeAd? { didSet {
        nativeAdView.nativeAd = nativeAdObject
        guard let native = nativeAdObject else { return }
        native.delegate = self
        
        // 标题
        titleLabel.text = native.headline
        // 内容
        bodyLabel.text = native.body
        
        // 媒体资源
        let mediaContent = native.mediaContent
        mediumView.mediaContent = mediaContent

        // // 小星星数量 (0 to 5).
        // let starRating = native.starRating ?? 0
        // print("-->toj: starRating: \(starRating)")
        // // 安装文案
        // let callToAction = native.callToAction ?? ""
        // print("-->toj: callToAction: \(callToAction)")
        // // 安装去向
        // let store = native.store ?? ""
        // print("-->toj: store: \(store)")
        // // 价钱
        // let price = native.price ?? ""
        // print("-->toj: price: \(price)")
        // // 广告商
        // let advertiser = native.advertiser ?? ""
        // print("-->toj: advertiser: \(advertiser)")
        // 广告图标
        // let adIcon = native.icon?.image
    } }
    
    /* iconView */
    private lazy var nativeAdView = GADNativeAdView()
    
    /* adFlagLabel */
    private lazy var adFlagLabel: UILabel = {
        let view = UILabel()
        view.textAlignment = .center
        view.backgroundColor = "#FFBE19".to_color
        view.textColor = .white
        view.font = 14.to_boldFont
        view.text = "AD"
        return view
    }()
    
    /* imageView */
    private(set) lazy var imageView: UIImageView = {
        let view = UIImageView()
        view.isHidden = false
        view.image = "com_placeholder_336x189".to_image
        return view
    }()
    
    /// 媒体资源
    private(set) lazy var mediumView: GADMediaView = {
        let view = GADMediaView()
        return view
    }()
    
    /* titleLabel */
    private(set) lazy var titleLabel: UILabel = {
        let view = UILabel()
        view.font = 14.to_boldFont
        return view
    }()
    
    /* bodyLabel */
    private(set) lazy var bodyLabel: UILabel = {
        let view = UILabel()
        view.font = 12.to_boldFont
        view.numberOfLines = 0
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupMakeAddSubviews()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        setupMakeLayoutSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        print("-->toj: STNativeAdmobView - deinit")
    }
    private var _adLoader: GADAdLoader?
}

extension STNativeAdmobView {
    
    func setUserInteractionToUse(_ isUse: Bool) {
        print("-->toj: isUse:\(isUse)")
        
        imageView.isHidden = isUse
        nativeAdView.isHidden = !isUse
        nativeAdView.isUserInteractionEnabled = isUse
    }
    
    func dispose() {
        _adLoader?.delegate = nil
        _adLoader = nil
    }
    
    func loadNativeAd(_ adModel: STAdmobModel?) {
        guard let model = adModel else {
            dispose()
            setUserInteractionToUse(false)
            return
        }
        
        admobModel = model
        let spaceID = model.space_id
        print("-->toj: class:\(cm_className), func: \(#function), spaceID: spaceID:\(spaceID),")
        
        if _adLoader?.isLoading == true {
            return
        }
        
        let isUse = nativeAdView.nativeAd != nil
        setUserInteractionToUse(isUse)
        
        let materials = model.materials
        let vc = UIViewController.vc_currentNavigationTopViewController
        
        let options = GADNativeAdViewAdOptions()
        options.preferredAdChoicesPosition = .topLeftCorner
        let adLoader = GADAdLoader(adUnitID: materials, rootViewController: vc,
                                   adTypes: [.native], options: [options])
        adLoader.delegate = self
        let request = GADRequest()
        adLoader.load(request)
        _adLoader = adLoader
    }
}

extension STNativeAdmobView: GADNativeAdLoaderDelegate {
    
    func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {
        setUserInteractionToUse(false)
        nativeAdView.isHidden = false
        
        let spaceID = admobModel?.space_id ?? ""
        print("-->toj:spaceID: \(spaceID), adLoader: didReceive")
        // 设置数据源
        nativeAdObject = nativeAd
        
        
        print("-->toj: aspectRatio:\(nativeAd.mediaContent.aspectRatio)")
        
//        let mediaContent = nativeAd.mediaContent
//        guard mediaContent.hasVideoContent else {
//            return
//        }
//        mediaContent.videoController.delegate = self
    }
    
    func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error)  {
        let spaceID = admobModel?.space_id ?? ""
        print("-->toj: spaceID:\(spaceID), didFailToReceiveAdWithError:\(error.localizedDescription)")
        setUserInteractionToUse(false)
    }
}

extension STNativeAdmobView: GADVideoControllerDelegate {
    
    func videoControllerDidEndVideoPlayback(_ videoController: GADVideoController) {
        
    }
}

// MARK: - GADNativeAdDelegate implementation
extension STNativeAdmobView: GADNativeAdDelegate {
    
    func nativeAdDidRecordImpression(_ nativeAd: GADNativeAd) {
        let spaceID = admobModel?.space_id ?? ""
        print("\(#function) called, spaceID:\(spaceID)")
        setUserInteractionToUse(true)
    }
    
//    func nativeAdDidRecordClick(_ nativeAd: GADNativeAd) {
//        print("\(#function) called")
//    }
//
//    func nativeAdWillPresentScreen(_ nativeAd: GADNativeAd) {
//        print("\(#function) called")
//    }
//
//    func nativeAdWillDismissScreen(_ nativeAd: GADNativeAd) {
//        print("\(#function) called")
//    }
//
//    func nativeAdDidDismissScreen(_ nativeAd: GADNativeAd) {
//        print("\(#function) called")
//    }
//
//    func nativeAdWillLeaveApplication(_ nativeAd: GADNativeAd) {
//        print("\(#function) called")
//    }
}

// MARK: - 初始化
extension STNativeAdmobView {
    
    private func setupMakeAddSubviews() {
        addSubview(nativeAdView)
        addSubview(imageView)
        
        // 点击事件基于内部控件上的, 所以给内部控件赋值才可以点击跳转
        nativeAdView.mediaView = mediumView
        nativeAdView.headlineView = titleLabel
        nativeAdView.bodyView = bodyLabel
        
        nativeAdView.addSubview(mediumView)
        nativeAdView.addSubview(titleLabel)
        nativeAdView.addSubview(bodyLabel)
        nativeAdView.addSubview(adFlagLabel)
    }
    
    private func setupMakeLayoutSubviews() {
        let height = adFlagLabel.cm_stringOneLineHeight
        let width = adFlagLabel.cm_stringOneLineWidth
        
        nativeAdView.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
        
        adFlagLabel.snp.remakeConstraints { make in
            make.top.right.equalTo(self).inset(3)
            make.height.equalTo(height + 2)
            make.width.equalTo(width + 5)
        }
    }
}
